import torch

# 准备数据集
# x_data和y_data是矩阵，3行1列，表示总共有3个数据点，每个数据点只有1个特征
x_data = torch.tensor([[1.0], [2.0], [3.0]])  # 输入数据x，3个样本，每个样本1个特征
y_data = torch.tensor([[2.0], [4.0], [6.0]])  # 输出数据y，3个样本的对应目标值，每个样本1个特征

# 定义线性模型类
class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        # 前向传播, 通过线性层计算预测值
        y_pred = self.linear(x)
        return y_pred

# 实例化线性模型
model = LinearModel()

criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)

# 训练循环: 前向传播、反向传播、参数更新
for epoch in range(10):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    print(epoch, loss.item())

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()


print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())

# 测试模型
x_test = torch.tensor([[4.0]])
y_test = model(x_test)

print("y_pred = ", y_test.data)